package com.ruoyi.system.controller;

import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.utils.IdUtils;
import com.ruoyi.common.core.utils.QiniuUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片文件上传
 */
@RestController
@RequestMapping("/img")
public class ImgDisposeController {

    @Value("${qiniu.oss.url}")
    private String qnOssUrl;
//    @Autowired
//    RedisService redisService;

    @PostMapping("/upload")
    @Log(title = "图片上传", businessType = BusinessType.OTHER)
    public AjaxResult imgQnUpload(@RequestParam("imgFile") MultipartFile file) {
        if (!file.isEmpty()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return AjaxResult.error("上传图片异常，请联系管理员");
            }

            String avatarFileName = loginUser.getSysUser().getAvatar();
            if (StringUtils.isNotEmpty(avatarFileName)) {
                String[] split = avatarFileName.split("/");
                QiniuUtils.deleteFileFromQiniu(split[split.length - 1]);
            }
            String fileName = IdUtils.fastUUID() + ".jpg";
            String resultFileName = qnOssUrl + fileName;

            try {
                QiniuUtils.upload2Qiniu(file.getBytes(), fileName);
                /*List<Object> cacheList = redisService.getCacheList(Constants.QI_NIU_FILE_REDIS_KEY);*/
//                if (cacheList != null && cacheList.size() >= 1) {
//                    cacheList.add(fileName);
//                }else {
//                    cacheList = new ArrayList<>();
//                    cacheList.add(fileName);
//                }
                /*redisService.setCacheList(Constants.QI_NIU_FILE_REDIS_KEY, cacheList);*/
            } catch (IOException e) {
                e.printStackTrace();
            }
            return AjaxResult.success("上传成功", resultFileName);
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }
}
